package com.example.guardian.client.spring.provider;

import com.example.guardian.client.proxy.InvokerHolder;
import com.example.guardian.client.util.ActionContextUtil;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 事务发起拦截器
 *
 * @author gang.wang 2021/12/8
 */
public class TransactionProviderInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        // 获取对应注解
        Method method = invocation.getMethod();
        Object[] args = invocation.getArguments();
        TransactionProvider transactionProvider = method.getAnnotation(TransactionProvider.class);
        if (transactionProvider != null) {
            Map<String, Object> context = ActionContextUtil.fetchActionRequestContext(method, args);
            String messageId = context.get("messageId").toString();
            InvokerHolder.get().confirmInvoke(messageId);
        }
        return invocation.proceed();
    }
}